package com.xxx.mch.aspject;

import com.xxx.mch.annotation.WithRole;
import com.xxx.mch.config.MchInterepter;
import com.xxx.mch.exception.BusinessException;
import java.lang.reflect.Method;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;

/**
 * @author FengHaixin
 * @description 一句话描述该文件的用途
 * @date 2020/9/22
 */
@Slf4j
@Aspect
@Component
@Order (Integer.MIN_VALUE + 1)
public class AccessValidateAspectj
{
    @Pointcut ("@annotation(com.xxx.mch.annotation.WithRole)")
    public void pointCut()
    {
    }


    @Around (value = "pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable
    {
        MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        WithRole withRole = method.getAnnotation(WithRole.class);
        if (Objects.isNull(withRole))
        {
            Class<?> aClass = joinPoint.getTarget().getClass();
            withRole = aClass.getAnnotation(WithRole.class);
        }
        if (Objects.isNull(withRole))
        {
            return joinPoint.proceed();
        }

        List<String> permissonCodeList = MchInterepter.UID.get().getPermissonCodeList();
        String[] needRoles = withRole.needRoles();
        if (Stream.of(needRoles).anyMatch(permissonCodeList::contains))
        {
            return joinPoint.proceed();
        }
        throw new BusinessException("无法访问，需要权限：" + StringUtils.joinWith(",", needRoles));
    }
}
